<?php
/**
 * 公共服务
 * Created by PhpStorm.
 * User: echa
 * Date: 2018/2/3
 * Time: 10:16
 */
namespace App\Services\Warehouse;
use function EasyWeChat\Kernel\data_to_array;
use function Sodium\add;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class PublicService {
    //表单ID
    protected  $FormId='';

    protected $HttpClientService;
    protected $ValidateUserService;
    public $userdata;

    public function __construct($FormId='',$OpenCheckLogin=true)
    {
        $this->HttpClientService=new HttpClientService();
        $this->FormId=$FormId;
        //登陆验证
        if($OpenCheckLogin){
            $this->userdata=$this->CheckLogin();
        }
    }


    public function  CheckLogin(){
        $url=$this->HttpClientService->config['WebUrl'].$this->HttpClientService->config['ValidateUser'];
        $data=[
            'acctID'=>$this->HttpClientService->config['k3uid'],
            'username'=>$this->HttpClientService->config['username'],
            'password'=>$this->HttpClientService->config['pass'],
            'lcid'=>$this->HttpClientService->config['lcid']
        ];
        $response=$this->HttpClientService->Http->request('POST',$url,[
            'form_params'=>$data,
        ],['cookies'=>$this->HttpClientService->CookieJar]);
        $res=json_decode((string) $response->getBody(), true);
        if($res['LoginResultType']==1){
            $ReturnData=[
                'LoginResultType'=>$res['LoginResultType'],
                'UserId'=>$res['Context']['UserId'],
                'UserName'=>$res['Context']['UserName'],
                'CustomName'=>$res['Context']['CustomName'],
                'DisplayVersion'=>$res['Context']['DisplayVersion'],
                'DataCenterName'=>$res['Context']['DataCenterName'],
                'UserToken'=>$res['Context']['UserToken'],
                'Message'=>$res['Message']
            ];
            return $ReturnData;
        }else{
            $data=[
                'LoginResultType'=>$res['LoginResultType'],
                'Message'=>$res['Message']
            ];
            return $data;
        }
    }



    /**
     *查看---已废弃
     *1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.CreateOrgId：创建者组织，字符串类型（非必录）
    2.2.Number：单据编号，字符串类型（用编号查询必录）
    2.3.Id：表的主键Id（用Id查询时必录）
     *
     */
    public  function view($Number='',$Id=''){
        $LoginResultType=$this->userdata['LoginResultType'];
        if($LoginResultType==1){
            if(empty($Number)){
                if(empty($Id)){
                    return $this->failed('参数错误：Number和Id参数务必传一个');
                }
            }
            $url=$this->HttpClientService->config['WebUrl'].$this->HttpClientService->config['ViewUrl'];
            $data= json_encode([
                'CreateOrgId'=>0,
                'Number'=>$Number,
                'Id'=>$Id
            ]);
            $response=$this->HttpClientService->Http->request('POST',$url,[
                'form_params'=>[
                    'formid'=>$this->FormId,
                    'data'=>$data
                ],
            ],['cookies' => $this->HttpClientService->CookieJar]);
            $res=json_decode((string) $response->getBody(), true);
            if($res['Result']['ResponseStatus']['IsSuccess']==false){
                throw new NotFoundHttpException ($res['Result']['ResponseStatus']['Errors']['Message']);
            }else{
                //$res['Result']['Result']
                $resturndata=[
                    'Id'=>$res['Result']['Result']['Id'],
                    'Number'=>$res['Result']['Result']['Number'],
                    'Name'=>$res['Result']['Result']['Name']['Value'],
                    'CreateDate'=>$res['Result']['Result']['CreateDate'],
                    'ModifyDate'=>$res['Result']['Result']['ModifyDate'],
                    'Specification'=>$res['Result']['Result']['Specification']['Value'],

                ];
                return $resturndata;
            }
        }else{
            throw new NotFoundHttpException($this->userdata['Message']);
        }
    }

    /**
    保存
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.Creator：创建者名字（非必录）
    2.2.NeedUpDateFields：需要保存的字段,格式["fieldkey1","fieldkey2","entitykey1",...]，数组类型(非必录)
    2.3.NeedReturnFields：需要返回的结果字段,格式["fieldkey","entitykey.fieldkey",...]（非必录）
    2.4.IsDeleteEntry：是否删除分录，默认True删除（非必录）
    2.5.SubSystemId：菜单所在子系统Id（非必录）
    2.6.IsVerifyBaseDataField：是否验证所有的基础资料，默认False不验证（非必录）
    2.7.IsEntryBatchFill：是否批量填充分录：默认为Ture（非必录）
    2.8.Model：表单实体数据（必录）
     */
    public function save($modeldata=[]){
        $LoginResultType=$this->userdata['LoginResultType'];
        if($LoginResultType==1){
            $url=$this->HttpClientService->config['WebUrl'].$this->HttpClientService->config['SaveUrl'];
            $data=json_encode(
                [
                    "Creator" => "",
                    "NeedUpDateFields" => [],
                    "NeedReturnFields" => [],
                    "IsDeleteEntry" => "True",
                    "SubSystemId" => "",
                    "IsVerifyBaseDataField" => "false",
                    "IsEntryBatchFill" => "True",
                    "Model" =>$modeldata
                 ]
            );
            $response=$this->HttpClientService->Http->request('POST',$url,[
                'form_params'=>[
                    'formid'=>$this->FormId,
                    'data'=>$data
                ],
            ],['cookies' => $this->HttpClientService->CookieJar]);
            $res=json_decode((string) $response->getBody(), true);
            if($res['Result']['ResponseStatus']['IsSuccess']==true){
                $returndata=[
                    'Id'=>$res['Result']['ResponseStatus']['SuccessEntitys'][0]['Id'],
                    'Number'=>$res['Result']['ResponseStatus']['SuccessEntitys'][0]['Number']
                ];
                return $returndata;
            }else{
                $str_error='';
                if(count($res['Result']['ResponseStatus']['Errors'])>0){
                    foreach ($res['Result']['ResponseStatus']['Errors'] as $k=>$v){
                        $str_error.=$v['Message'].'\r\n';
                    }
                }
                throw new NotFoundHttpException($str_error);
            }
        }else{
            throw new NotFoundHttpException($this->userdata['Message']);
        }

    }


    /**
    批量保存
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.NumberSearch：是否使用Number来搜索基础资料，默认为True（非必录）
    2.2.ValidateFlag：是否验证标志，布尔类型,默认为True（非必录）
    2.3.IsDeleteEntry：是否删除分录，默认True删除（非必录）
    2.4.NeedUpDateFields：需要保存的字段,格式["fieldkey1","fieldkey2","entitykey1",...]，数组类型(非必录)
    2.5.NeedReturnFields：需要返回的结果字段,格式["fieldkey","entitykey.fieldkey",...]（非必录）
    2.6.SubSystemId：菜单所在子系统Id（非必录）
    2.7.Model：表单实体数据（必录）
    2.8.BatchCount：批量保存线程数，整形（非必录）

     */
    public function batchsave($modeldata){
        $LoginResultType=$this->userdata['LoginResultType'];
        if($LoginResultType==1){
            $url=$this->HttpClientService->config['WebUrl'].$this->HttpClientService->config['BatchSaveUrl'];
            $data=json_encode([
                "Creator" => "",
                "NeedUpDateFields" => [],
                "NeedReturnFields" => [],
                "IsDeleteEntry" => "True",
                "SubSystemId" => "",
                "IsVerifyBaseDataField" => "false",
                "IsEntryBatchFill" => "True",
                "BatchCount"=>1,
                "Model" =>$modeldata
            ]);
            $response=$this->HttpClientService->Http->request('POST',$url,[
                'form_params'=>[
                    'formid'=>$this->FormId,
                    'data'=>$data
                ],
            ],['cookies' => $this->HttpClientService->CookieJar]);
            $res=json_decode((string) $response->getBody(), true);
            if($res['Result']['ResponseStatus']['IsSuccess']==true){
                $returndata=[
                    'Id'=>$res['Result']['Id'],
                    'Number'=>$res['Result']['Number']
                ];
                return $returndata;
            }else{
                throw new NotFoundHttpException($res['Result']['ResponseStatus']['Errors']['Message']);
            }
        }else{
            throw new NotFoundHttpException($this->userdata['Message']);
        }

    }

    /**
    提交
     *1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.CreateOrgId：创建者组织，字符串类型（非必录）
    2.2.Numbers：单据编号集合，格式["billNo1","billNo1",...]，数组类型（必录）
     */
    public function  submit($Numbers=[]){
        $LoginResultType=$this->userdata['LoginResultType'];
        if($LoginResultType==1){
            $url=$this->HttpClientService->config['WebUrl'].$this->HttpClientService->config['SubmitUrl'];
            $data=json_encode([
                'CreateOrgId'=>0,
                'Numbers'=>$Numbers
            ]);
            $response=$this->HttpClientService->Http->request('POST',$url,[
                'form_params'=>[
                    'formid'=>$this->FormId,
                    'data'=>$data
                ],
            ],['cookies' => $this->HttpClientService->CookieJar]);
            $res=json_decode((string) $response->getBody(), true);
            if($res['Result']['ResponseStatus']['IsSuccess']){
                $returndata=[
                    'Id'=>$res['Result']['ResponseStatus']['SuccessEntitys'][0]['Id'],
                    'Number'=>$res['Result']['ResponseStatus']['SuccessEntitys'][0]['Number']
                ];
                return $returndata;
            }else{
                $str_error='';
                if(count($res['Result']['ResponseStatus']['Errors'])>0){
                    foreach ($res['Result']['ResponseStatus']['Errors'] as $k=>$v){
                        $str_error.=$v['Message'].'\r\n';
                    }
                }
                throw new NotFoundHttpException($str_error);
            }
        }else{
            throw new NotFoundHttpException($this->userdata['Message']);
        }
    }

    /**
    审核
     *
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.CreateOrgId：创建者组织，字符串类型（非必录）
    2.2.Numbers：单据编号集合，格式["billNo1","billNo1",...]，数组类型（必录）

     */
    public function audit($Numbers=[]){
        $LoginResultType=$this->userdata['LoginResultType'];
        if($LoginResultType==1){
            $url=$this->HttpClientService->config['WebUrl'].$this->HttpClientService->config['AuditUrl'];
            $data=json_encode([
                'CreateOrgId'=>0,
                'Numbers'=>$Numbers
            ]);
            $response=$this->HttpClientService->Http->request('POST',$url,[
                'form_params'=>[
                    'formid'=>$this->FormId,
                    'data'=>$data
                ],
            ],['cookies' => $this->HttpClientService->CookieJar]);
            $res=json_decode((string) $response->getBody(), true);
            if($res['Result']['ResponseStatus']['IsSuccess']==true){
                $returndata=[
                    'Id'=>$res['Result']['ResponseStatus']['SuccessEntitys'][0]['Id'],
                    'Number'=>$res['Result']['ResponseStatus']['SuccessEntitys'][0]['Number']
                ];
                return $returndata;
            }else{
                $str_error='';
                if(count($res['Result']['ResponseStatus']['Errors'])>0){
                    foreach ($res['Result']['ResponseStatus']['Errors'] as $k=>$v){
                        $str_error.=$v['Message'].'\r\n';
                    }
                }
                throw new NotFoundHttpException($str_error);
            }
        }else{
            throw new NotFoundHttpException($this->userdata['Message']);
        }
    }

    /**
    反审核
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.CreateOrgId：创建者组织，字符串类型（非必录）
    2.2.Numbers：单据编号集合，格式["billNo1","billNo1",...]，数组类型（必录）
     */
    public function unAudit($Numbers=[]){
        $LoginResultType=$this->userdata['LoginResultType'];
        if($LoginResultType==1) {
            $url = $this->HttpClientService->config['WebUrl'] . $this->HttpClientService->config['UnAuditUrl'];
            $data = json_encode(['CreateOrgId' => 0, 'Numbers' => $Numbers]);
            $response = $this->HttpClientService->Http->request('POST', $url, ['form_params' => ['formid' => $this->FormId, 'data' => $data],], ['cookies' => $this->HttpClientService->CookieJar]);
            $res = json_decode((string)$response->getBody(), true);
            if($res['Result']['ResponseStatus']['IsSuccess']==true){
                $returndata=[
                    'Id'=>$res['Result']['ResponseStatus']['SuccessEntitys'][0]['Id'],
                    'Number'=>$res['Result']['ResponseStatus']['SuccessEntitys'][0]['Number']
                ];
                return $returndata;
            }else{
                $str_error='';
                if(count($res['Result']['ResponseStatus']['Errors'])>0){
                    foreach ($res['Result']['ResponseStatus']['Errors'] as $k=>$v){
                        $str_error.=$v['Message'].'\r\n';
                    }
                }
                throw new NotFoundHttpException($str_error);
            }
        }else{
            throw new NotFoundHttpException($this->userdata['Message']);
        }
    }

    /**
     *单据列表查询
     * 1.data：Json格式数据（详情参考Json格式数据）（必录）
    1.1.FormId：业务对象表单Id（必录）
    1.2.FieldKeys：字段keys，字符串类型用逗号分隔，比如"key1,key2..."（必录）
    1.3.FilterString：过滤（非必录）  FNumber=''
    1.4.OrderString：排序字段（非必录）
    1.5.TopRowCount：总行数（非必录）
    1.6.StartRow：开始行（非必录）
    1.7.Limit：最大行数，不能超过2000（非必录）
     */
    public function ExecuteBillQuery($FieldKeys='',$FilterString='',$OrderString='',$TopRowCount=0,$StartRow=0,$Limit=20)
    {

        if ($this->userdata['LoginResultType'] == 1) {
            if ($Limit > 2000) {
                $Limit=2000;
            }
            if(empty($TopRowCount)){
                $TopRowCount=0;
            }
            if(empty($StartRow)){
                $StartRow=0;
            }
            $url = $this->HttpClientService->config['WebUrl'] . $this->HttpClientService->config['ExecuteBillQueryUrl'];
            $data = json_encode(
                [
                    'FormId' => $this->FormId,
                    'FieldKeys' => $FieldKeys,
                    'FilterString' => $FilterString,
                    'OrderString' => $OrderString,
                    'TopRowCount' => $TopRowCount,
                    'StartRow' => $StartRow,
                    'Limit' => $Limit
                ]);
            $response = $this->HttpClientService->Http->request('POST', $url,[
                    'form_params'=>[
                        'data'=>$data
                    ],
                ],['cookies' => $this->HttpClientService->CookieJar]);
            $ReturnData=json_decode((string)$response->getBody(), true);
            if(count($ReturnData)>0){
                $FieldKeys=explode(",",$FieldKeys);
                $Return=array();
                foreach ($ReturnData as $key=>$val){
                    $Return[]=array_combine($FieldKeys,$val);
                }
                return $Return;
            }else{
                return $ReturnData;
            }
        }else{
            throw new NotFoundHttpException($this->userdata['Message']);
        }
    }

    /**
     *  单据操作的通用接口
     *1.formid：业务对象表单Id（必录）
    2.opNumber：操作类型（必录）
    3.data：Json格式数据（详情参考Json格式数据）（必录）
    3.1.CreateOrgId：创建者组织，字符串类型（非必录）
    3.2.Numbers：单据编号集合，数组类型，格式["billNo1","billNo1",...]，数组类型（必录）
    3.3.Ids：单据内码，字符串类型，格式"Id1,Id2,..."（逗号分开，未传Numbers，则必录）
     */
    public function ExcuteOperation($Numbers=[],$opNumber){
        if ($this->userdata['LoginResultType'] == 1) {
            $url=$this->HttpClientService->config['WebUrl'].$this->HttpClientService->config['ExcuteOperation'];
            $data=json_encode([
                'CreateOrgId'=>0,
                'Numbers'=>$Numbers
            ]);
            $response=$this->HttpClientService->Http->request('POST',$url,[
                'form_params'=>[
                    'formid'=>$this->FormId,
                    'opNumber'=>$opNumber,//config('k3cloud.opNumberCancel')
                    'data'=>$data
                ],
            ],['cookies' => $this->HttpClientService->CookieJar]);
            $res=json_decode((string) $response->getBody(), true);
            if($res['Result']['ResponseStatus']['IsSuccess']==true) {
                $returndata = ['Id' => $res['Result']['ResponseStatus']['SuccessEntitys'][0]['Id'], 'Number' => $res['Result']['ResponseStatus']['SuccessEntitys'][0]['Number']];
                return $returndata;
            }else{
                $str_error='';
                if(count($res['Result']['ResponseStatus']['Errors'])>0){
                    foreach ($res['Result']['ResponseStatus']['Errors'] as $k=>$v){
                        $str_error.=$v['Message'].'\r\n';
                    }
                }
                 throw new NotFoundHttpException($str_error);
            }
        }else{
            throw new NotFoundHttpException($this->userdata['Message']);
        }
    }

    /***
     * 下推
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.Ids：单据内码，字符串类型，格式"Id1,Id2,..."（逗号分开，未传Numbers，则必录）
    2.2.Numbers：单据编号集合，数组类型，格式["billNo1","billNo1",...]，数组类型（必录）
    2.3.RuleId：转换规则内码，字符串类型，格式"RuleId"（未启用默认转换规则时，则必录）
    2.4.TargetBillTypeId：目标单据类型内码，字符串类型，格式"Id1"（非必录）
    2.5.TargetOrgId：目标组织内码，整数类型，格式"Id1"（非必录）
    2.6.TargetFormId：目标单据FormId，字符串类型，格式:"FormId"（启用默认转换规则时，则必录）
    2.7.IsEnableDefaultRule：是否启用默认转换规则，布尔类型，默认值False，格式"false"（非必录）
    2.8.CustomParams：自定义参数，字典类型，格式"{key1:value1,key2:value2,...}"（非必录）
     * @param array $Numbers
     * @param $RuleId   转换规则内码
     * @param $TargetFormId  目标单据FormId
      @author echa
     */
    public function PushedDown($Numbers=[],$RuleId,$TargetFormId){
        if ($this->userdata['LoginResultType'] == 1) {
            $url=$this->HttpClientService->config['WebUrl'].$this->HttpClientService->config['Push'];
            $data=json_encode([
                'RuleId'=>$RuleId,
                'Numbers'=>$Numbers,
                'TargetFormId'=>$TargetFormId
            ]);
            $response=$this->HttpClientService->Http->request('POST',$url,[
                'form_params'=>[
                    'formid'=>$this->FormId,
                    'data'=>$data
                ],
            ],['cookies' => $this->HttpClientService->CookieJar]);
            $res=json_decode((string) $response->getBody(), true);
            if($res['Result']['ResponseStatus']['IsSuccess']==true) {
                $returndata = ['Id' => $res['Result']['ResponseStatus']['SuccessEntitys'][0]['Id'], 'Number' => $res['Result']['ResponseStatus']['SuccessEntitys'][0]['Number']];
                return $returndata;
            }else{
                $str_error='';
                if(count($res['Result']['ResponseStatus']['Errors'])>0){
                    foreach ($res['Result']['ResponseStatus']['Errors'] as $k=>$v){
                        $str_error.=$v['Message'].'\r\n';
                    }
                }
                throw new NotFoundHttpException($str_error);
            }
        }else{
            throw new NotFoundHttpException($this->userdata['Message']);
        }
    }

    /**
    *   单据状态对应转换
     */
    public function DocumentStatus($Key=''){
        $DocumentStatus=[
            'A'=>'创建',
            'B'=>'审核中',
            'C'=>'已审核',
            'D'=>'重新审核',
            'Z'=>'暂存',
        ];
        return $DocumentStatus[$Key];
    }

    /**
    *   禁用状态转换
     */
    public function ForbidStatus($Key=''){
        $ForbidStatus=[
            'A'=>'否',
            'B'=>'是'
        ];
        return $ForbidStatus[$Key];
    }


}
